﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour {

	public bool isAnimating = false;
	public float attackY;
	public float attackRange;
	public float moveSpeed;
	protected Transform player;
	protected Rigidbody2D rb;
	protected Animator animator;
	protected Vector2 moveDir;

	void Start()
	{
		player = PlayerController.GetInstance().transform;
		rb = GetComponent<Rigidbody2D>();
		animator = GetComponent<Animator>();
        if (!animator)
        {
			animator = GetComponentInChildren<Animator>();
        }
	}

	protected float GetDeltaYBetween()
	{
		float playerY = player.position.y;
		float enemyY = transform.position.y;
		return Mathf.Abs(playerY - enemyY);
	}

	protected float GetPlayerDistance()
	{
		Vector3 playerPos = player.position;
		return Vector3.Distance(playerPos, transform.position);
	}

	protected bool IsInAttackRange()
    {
		float deltaY = GetDeltaYBetween();
		float distance = GetPlayerDistance();
		if (distance < attackRange && deltaY < attackY)
		{
			return true;
		}
		return false;
	}

	protected bool IsInAttackXRange()
    {
		float distance = GetPlayerDistance();
		if (distance <= attackRange)
        {
			return true;
		}
		return false;
	}

	protected bool IsInAttackYRange()
	{
		float deltaY = GetDeltaYBetween();
		if (deltaY < attackY)
		{
			return true;
		}
		return false;
	}

	protected void AnimateWalkAndGetDir()
	{
		animator.SetBool("Walking", true);
		moveDir = (player.position - transform.position).normalized;
	}

	protected void AnimateWalkYDir()
    {
		animator.SetBool("Walking", true);
		Vector2 dir = new Vector2(transform.position.x, player.position.y);
		moveDir = (dir - new Vector2(transform.position.x, transform.position.y)).normalized;
	}

	protected void AnimateWalkXDir()
	{
		animator.SetBool("Walking", true);
		Vector2 dir = new Vector2(player.position.x, transform.position.y);
		moveDir = (dir - new Vector2(transform.position.x, transform.position.y)).normalized;
	}

	protected void FlipEnemy()
	{
		Vector3 playerPos = PlayerController.GetInstance().transform.position;
		//玩家在怪物的右边还是左边
		if (playerPos.x > transform.position.x)
		{
			transform.localEulerAngles = new Vector3(0, 0, 0);
		}
		else
		{
			transform.localEulerAngles = new Vector3(0, 181, 0);
		}
	}

}
